<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/11
 * Time: 9:32
 */

namespace zhtfrontend\controllers;

use common\models\datas\IsuserInfo;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;
use zhtfrontend\components\services\commission\Settlement;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\CommissionSettlement;
use zhtfrontend\models\datas\CommissionSettlementRelation;
use zhtfrontend\models\datas\Orders;
use zhtfrontend\models\datas\OrdersCommission;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\SettlementVoucher;
use yii\data\Pagination;

class IsusercommissionController extends \zhtfrontend\components\bases\BaseController
{
    /*
     * 佣金类型
     */
    public $type = 0;

    /**
     * @结算列表页-以发卡认为单位
     * 1、Details
     * 2、Balance
     * 3、Detailshistory
     */
    public function actionIndex()
    {
        $param = \Yii::$app->request->get();
        $model = OrdersCommission::find()->where(['type' => $this->type]);
        if (!empty($param['start_time']) && !empty($param['end_time'])) {
            $start_time = strtotime(trim($param['start_time']));
            $end_time = strtotime(trim($param['end_time']) . ' 23:59:59');
        } else {
            $start_time = strtotime(date('Y-m-01', strtotime('-1 month')));
            $end_time = strtotime(date('Y-m-t 23:59:59', strtotime('-1 month')));
        }
        $model->andWhere(['between', 'created_at', $start_time, $end_time]);
        if (!empty($param['salesman'])) {
            $salesman_id = IsuserInfo::find()->select('id')->where(['like', 'contact', $param['salesman']])->column();
            $model->andWhere(['in', 'salesman_id', $salesman_id]);
        }
        $model->groupBy('salesman_id');
        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => 12]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $data = $model->offset($pages->offset)->limit($pages->limit)->asArray()->all();

        foreach ($data as $k => $v) {
            $unsettled = OrdersCommission::find()->where(['status' => 0, 'salesman_id' => $v['salesman_id']]);
            $settled = OrdersCommission::find()->where(['status' => 1, 'salesman_id' => $v['salesman_id']]);
            $settled_all = OrdersCommission::find()->where(['salesman_id' => $v['salesman_id']]);
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $start_time = strtotime(trim($param['start_time']));
                $end_time = strtotime(trim($param['end_time']) . ' 23:59:59');
            } else {
                $start_time = strtotime(date('Y-m-01', strtotime('-1 month')));
                $end_time = strtotime(date('Y-m-t 23:59:59', strtotime('-1 month')));
            }
            $unsettled->andWhere(['between', 'created_at', $start_time, $end_time]);
            $settled->andWhere(['between', 'created_at', $start_time, $end_time]);
            $data[$k]['count'] = $settled_all->count(1);
            $data[$k]['all_money'] = empty($settled_all->sum('settlement_amount')) ? '0.00' : $settled_all->sum('settlement_amount');
            $data[$k]['settled_count'] = $settled->count(1);
            $data[$k]['settled_money'] = empty($settled->sum('settlement_amount')) ? '0.00' : $settled->sum('settlement_amount');
            $data[$k]['unsettled_count'] = $unsettled->count(1);
            $data[$k]['unsettled_money'] = empty($unsettled->sum('settlement_amount')) ? '0.00' : $unsettled->sum('settlement_amount');
            $salesman = IsuserInfo::findOne($v['salesman_id']);
            $data[$k]['salesman'] = $salesman->contact;
        }

        $start = !empty($param['start_time']) ? $param['start_time'] : date('Y-m-d', $start_time);
        $end = !empty($param['end_time']) ? $param['end_time'] : date('Y-m-d', $end_time);
        return $this->render('index', ['data' => $data, 'pages' => $pages, 'start' => $start, 'end' => $end]);
    }

    /**
     * @查询当前发卡人的所有结算项----时间限制 默认上月
     * 1、balance
     */
    public function actionDetails()
    {
        $param = \Yii::$app->request->get();
        if (empty($param)) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = OrdersCommission::find()->where(['salesman_id' => $param['salesman_id'], 'type' => $this->type]);
        if (!empty($param['time_start']) && !empty($param['time_end'])) {
            $time_start = strtotime($param['time_start']);
            $time_end = mktime(23, 59, 59, date('m', strtotime($param['time_start'])) + 1, 00);
            $model->andWhere(['between', 'created_at', $time_start, $time_end]);
            $date['start'] = $param['time_start'];
            $date['end'] = $param['time_end'];
        }
        if (!empty($param['orders'])) {
            $orders = Orders::find()->select('id')->where(['like', 'sn', $param['orders']])->column();
            $model->andWhere(['in', 'orders_id', $orders]);
        }
        if (!empty($param['status'])) {
            $model->andWhere(['status' => $param['status']]);
        }
        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => 12]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $orders_commission = $model->offset($pages->offset)->limit($pages->limit)->all();
        $data_arr = [];
        foreach ($orders_commission as $k => $v) {
            $data_arr[$k] = [
                'orders' => $v->orders->sn,
                'created_at' => date('Y-m-d H:i:s', $v->created_at),
                'status' => $v->status == 0 ? '未结算' : '已结算',
                'salesman' => $v->salesman->contact,
                'settlement_amount' => $v->settlement_amount,
                'commission_money' => $v->commission_money,
                'id' => $v->id,
                'status_n' => $v->status,
            ];
        }
        return $this->render('details', ['data_arr' => $data_arr, 'date' => $date]);
    }

    /**
     * @结算页面
     * ajax处理数据 balance
     *
     */
    public function actionBalance()
    {
        $search_data = \Yii::$app->request->get();
        if (isset($search_data['orders_commission_id'])) {
            if ($search_data['orders_commission_id'] == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
            }
            $orders_commission = OrdersCommission::findOne([$search_data['orders_commission_id']]);
            $data_arr = [
                'salesman' => $orders_commission->salesman->contact,
                'orders_count' => 1,
                'settlement_amount' => $orders_commission->settlement_amount,
                'commission_money' => $orders_commission->commission_money,
            ];
            $data_arr['details'][] = [
                'orders' => $orders_commission->orders->sn,
                'created_at' => date('Y-m-d H:i:s', $orders_commission->created_at),
//                'status' => $v->status == 0 ? '未结算' : '已结算',
//                'salesman' => $v->salesman->contact,
                'settlement_amount' => $orders_commission->settlement_amount,
                'commission_money' => $orders_commission->commission_money,
                'id' => $orders_commission->id,
            ];
        }
        if (isset($search_data['salesman_id'])) {
            if ($search_data['salesman_id'] == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
            }
            $data = OrdersCommission::find()->where(['salesman_id' => $search_data['salesman_id'], 'status' => 0, 'type' => $this->type]);
            if (!empty($param['time_start']) && !empty($param['time_end'])) {
                $time_start = strtotime($param['time_start']);
                $time_end = mktime(23, 59, 59, date('m', strtotime($param['time_start'])) + 1, 00);
                $data->andWhere(['between', 'created_at', $time_start, $time_end]);
                $date['start'] = $param['time_start'];
                $date['end'] = $param['time_end'];
            }
            $orders_commission = $data->all();
            $orders_count = 0;
            $settlement_amount_all = 0;
            $commission_money_all = 0;
            foreach ($orders_commission as $k => $v) {
                $orders_count++;
                $settlement_amount_all += $v->settlement_amount;
                $commission_money_all += $v->commission_money;
            }
            $salesman = IsuserInfo::findOne([$search_data['salesman_id']]);
            $data_arr = [
                'salesman' => $salesman->contact,
                'orders_count' => $orders_count,
                'settlement_amount' => $settlement_amount_all,
                'commission_money' => $commission_money_all,
                'details' => [],
            ];

            foreach ($orders_commission as $k => $v) {
                $data_arr['details'][$k] = [
                    'id' => $v->id,
                    'orders' => $v->orders->sn,
                    'created_at' => date('Y-m-d H:i:s', $v->created_at),
                    'settlement_amount' => $v->settlement_amount,
                    'commission_money' => $v->commission_money,
                ];
            }
        }

        return $this->render('balance', ['data' => $data_arr]);
    }

    /**
     * @结算
     * 接受ajax数据 进行结算
     */
    public function actionDobalance()
    {
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $post = \Yii::$app->request->post();
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                $ids = explode(',', $post['orders_commission_ids']);
                Fun::getSiteDb()->createCommand()->update('{{%orders_commission}}', ['status' => 1, 'settlement_time' => time()], ['in', 'id', $ids, 'status' => 0])->execute();
                $settlement_amount = 0;
                $commission_money = 0;
                foreach ($ids as $k => $v) {
                    $orders_commissions = OrdersCommission::findOne($v);
                    $settlement_amount += $orders_commissions->settlement_amount;
                    $commission_money += $orders_commissions->commission_money;
                }
                $orders_commission = OrdersCommission::findOne([$ids[0]]);
                $model = new CommissionSettlement();
                $model->salesman_id = $orders_commission->salesman_id;
                $model->type = $this->type;
                $model->settlement_amount = $settlement_amount;
                $model->commission_money = $commission_money;
                $model->operator_id = \Yii::$app->user->id;
                $model->operator = \Yii::$app->user->identity->username;
                if ($model->save(false)) {
                    foreach ($ids as $k => $v) {
                        $relation = new CommissionSettlementRelation();
                        $relation->settlement_id = $model->id;
                        $relation->orders_commission_id = $v;
                        $relation->save(false);
                    }
                }
                $transaction->commit();
                $data = [
                    'resault' => '结算成功',
                    'url' => Fun::url(['isusercommission/detailshistory', 'commission_settlement_id' => $model->id]),
                ];
                return $data;
            } catch (\Exception $e) {
                $transaction->rollBack();
                $data = [
                    'resault' => '结算失败',
                    'url' => '',
                ];
                return $data;
            }
        }
    }

    /**
     * @结算历史
     * 1、确认付款 Dosettlement
     * 2、付款详情 Detailssettlement
     * 3、上传凭证 Uploadvoucher
     */
    public function actionDetailshistory()
    {
        $search_data = \Yii::$app->request->get();
        if (isset($search_data['orders_commission_id'])) {
            if ($search_data['orders_commission_id'] == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 400);
            }
            $commission_settlement_id = CommissionSettlementRelation::find()->where(['orders_commission_id' => $search_data['orders_commission_id']])->one();
            $commission_settlement = CommissionSettlement::findOne($commission_settlement_id->settlement_id);
            $data[] = [
                'id' => $commission_settlement->id,
                'salesman' => $commission_settlement->salesman->contact,
                'status' => $commission_settlement->status == 0 ? '未付款' : '已付款',
                'settlement_amount' => $commission_settlement->settlement_amount,
                'commission_money' => $commission_settlement->commission_money,
                'operator' => $commission_settlement->operator,
                'created_at' => date('Y-m-d H:i:s', $commission_settlement->created_at),
                'status_n' => $commission_settlement->status,
                'is_all' => 0,
            ];
        } elseif (isset($search_data['commission_settlement_id'])) {
            if ($search_data['commission_settlement_id'] == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
            }
            $commission_settlement = CommissionSettlement::findOne($search_data['commission_settlement_id']);
            $data[] = [
                'id' => $commission_settlement->id,
                'salesman' => $commission_settlement->salesman->contact,
                'status' => $commission_settlement->status == 0 ? '未付款' : '已付款',
                'settlement_amount' => $commission_settlement->settlement_amount,
                'commission_money' => $commission_settlement->commission_money,
                'operator' => $commission_settlement->operator,
                'created_at' => date('Y-m-d H:i:s', $commission_settlement->created_at),
                'status_n' => $commission_settlement->status,
                'is_all' => 1,
            ];
        } elseif (isset($search_data['salesman_id'])) {
            if ($search_data['salesman_id'] == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
            }
            $commission_settlement = CommissionSettlement::find()->where(['salesman_id' => $search_data['salesman_id']]);
            $commission_settlement = $commission_settlement->all();
            $data = [];
            foreach ($commission_settlement as $k => $v) {
                $data[$k] = [
                    'id' => $v->id,
                    'status_n' => $v->status,
                    'salesman' => $v->salesman->contact,
                    'status' => $v->status == 0 ? '未付款' : '已付款',
                    'settlement_amount' => $v->settlement_amount,
                    'commission_money' => $v->commission_money,
                    'operator' => $v->operator,
                    'created_at' => date('Y-m-d H:i:s', $v->created_at),
                    'is_all' => 1,
                ];
            }
        }

        return $this->render('detailshistory', ['data' => $data]);
    }

    /**
     * @付款--上传凭证
     */
    public function actionDosettlement()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $commission_settlement_id = \Yii::$app->request->get('commission_settlement_id');
        if ($commission_settlement_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = CommissionSettlement::findOne($commission_settlement_id);
        if ($model == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        $payment = \Yii::$app->params['payment'];
        $admin = Admin::find()->where(['role' => 'finance'])->all();
        $finance = [];
        foreach ($admin as $k => $v) {
            $finance[$v->id] = $v->name;
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $postdata = \Yii::$app->request->post();
            $model->status = 1;
            $model->created_at_settlement = time();
            $model->payment_id = $postdata['CommissionSettlement']['payment_id'];
            $model->payment_method = $payment[$postdata['CommissionSettlement']['payment_id']];
            $model->payment_finance_id = $postdata['CommissionSettlement']['payment_finance_id'];
            $model->payment_finance_name = $finance[$postdata['CommissionSettlement']['payment_finance_id']];
            if ($model->save(false)) {
                $imagelist = $postdata['CommissionSettlement']['imageList'];
                if (Settlement::UploadImg($imagelist, $commission_settlement_id, $this->type)) {
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '付款成功'), Fun::url(['isusercommission/index']));
                } else {
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '付款失败'), Fun::url(['isusercommission/index']));
                }
            }
        }
        return $this->render('dosettlement', ['model' => $model, 'payment' => $payment, 'finance' => $finance]);
    }

    /**
     * 查看详情
     */
    public function actionDetailssettlement()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $get = \Yii::$app->request->get();
        if ($get['commission_settlement_id'] == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 400);
        }
        $relation = CommissionSettlementRelation::find()->where(['settlement_id' => $get['commission_settlement_id']])->all();
        $data_arr = [];
        foreach ($relation as $k => $v) {
            $commission_settlement = OrdersCommission::findOne($v->orders_commission_id);
            $data_arr[$k] = [
                'orders' => $commission_settlement->orders->sn,
                'salesman' => $commission_settlement->salesman->contact,
                'status' => $commission_settlement->status == 0 ? '未结算' : '已结算',
                'settlement_time' => $commission_settlement->settlement_time == 0 ? '--' : date('Y-m-d H:i:s', $commission_settlement->settlement_time),
                'settlement_amount' => $commission_settlement->settlement_amount,
                'commission_money' => $commission_settlement->commission_money,
                'orders_time' => date('Y-m-d H:i:s', $commission_settlement->orders->created_at),
                'created_at' => date('Y-m-d H:i:s', $commission_settlement->created_at),
                'proportion' => $commission_settlement->proportion * 0.01,
                'status_n' => $get['status_n'] == 0 ? '未付款' : '已付款',
            ];
        }

        $settlement_voucher = SettlementVoucher::find()->where(['settlement_id' => $get['commission_settlement_id']])->all();
        $img_arr = [];
        foreach ($settlement_voucher as $k => $v) {
            $img_arr[$k] = $v->voucher_url;
        }
        return $this->render('detailssettlement', ['data_arr' => $data_arr, 'img_arr' => $img_arr]);
    }

    /**
     * @继续上传凭证
     */
    public function actionUploadvoucher()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $commission_settlement_id = \Yii::$app->request->get('commission_settlement_id');
        if ($commission_settlement_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 400);
        }
        $model = CommissionSettlement::findOne($commission_settlement_id);
        if ($model == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 400);
        }
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $postdata = \Yii::$app->request->post();
            $imagelist = $postdata['CommissionSettlement']['imageList'];

            if (Settlement::UploadImg($imagelist, $commission_settlement_id, $this->type)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '上传成功'), Fun::url(['isusercommission/index']));
            } else {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '上传失败'), Fun::url(['isusercommission/index']));
            }
        }
        return $this->render('uploadvoucher', ['model' => $model]);
    }


}